const { setup } = require("@babel/traverse/lib/path/context");

class HookCodeFactory{
    callTapsSeries({onDone}){
        let taps = this.options.taps;
        if(taps.length==0){
            return '';//返回_callback()
        }
        let code = "";
        let current = onDone;
        for(let i=0;i<taps.length;i++){
           code += this.callTap(i)
        }
    //    for(let i=0;i<this.options.taps.length;i++){
    //        let content = this.callTap(i);
    //        code+=content;
    //    }
       return code;
    }
    //onDOne是每一个执行函数的回调
    callTap(tabIndex){
        let code = "";
        let interceptors = this.options.interceptors
        if(interceptors.length>0){
            if(interceptors[i].tap){
                code += `_interceptors[${i}].call(_tap${tapIndex});\n`
            }
        }
        code += `var _fn${tapIndex} = _x[${tapIndex}];\n`;
        let tapIndex = this.options.taps[tapIndex];
        switch(tapInfo.type){
            case "sync":
                code += `_fn${tapIndex}(${this.args});\n`;
                break;
            case "async":
                break
            default:
                break;
        }
        return code
    }
    init(options){
        this.options = options
    }
    //销毁
    deinit(options){
        this.options = null
    }
    args(options={}){
        let allArgs = this.options.args
        if(allArgs.length>0){
            return allArgs.join(', ');//name,age
        }
        return ''
    }
    header(){
        let code = ''
        code += `var _x = this._x;\n`;
        let interceptors  = this.options.interceptors;
        if(this.options.interceptors.length>0){
            code +=`var _taps = this.taps`;
            code += `var _interceptors = this.interceptors;`;
            for(let i=0;i<interceptors.length;i++){
                if(interceptors[i].call)
                    code += `_interceptors[${i}].call(${this.args()});\n`;
            }
        }
        return code
    }
    content(){
        throw new Error('此类方法：此方法需要子类重写');
    }
    setup(hookInstance,options){
        //把事件函数的数组赋给hook实例的_x属性
        hookInstance._x = options.taps.map(item=>item.fn)
    }
    create(options){
        this.init(options);//{args,taps,type}
        let fn;
        switch(options.type){
            case "sync":
                fn = new Function(this.args(),this.header()+this.content())
        }
        this.deinit();
    }
}